<?php
declare(strict_types=1);

namespace App\Exception\Handler;

use App\Core\Response;
use App\Exception\SessionValidException;
use Throwable;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpServer\Contract\RequestInterface;

class SessionValidExceptionHandler extends ExceptionHandler
{
    /**
     * @Inject
     *
     * @var \Hyperf\HttpServer\Contract\ResponseInterface as httpResponse
     */
    protected $httpResponse;

    /**
     * @Inject
     * @var Response
     */
    protected $apiResponse;
    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;
    /**
     * 异常处理.
     *
     * @param Throwable         $throwable
     * @param ResponseInterface $response
     *
     * @return ResponseInterface
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 判断被捕获到的异常是希望被捕获的异常
        if ($throwable instanceof SessionValidException) {
            // 阻止异常冒泡
            $this->stopPropagation();
            //判断是否为ajax提交
            $ajaxRequest = $this->request->getHeader('X-Requested-With');
            if(count($ajaxRequest)&&$ajaxRequest[0]=='XMLHttpRequest'){
                return $this->apiResponse->error(401,'请登录');
            }
            $redirct=urldecode($this->request->url());
//            这里我不想让他报 "Internal Server Error."这个错误，所以返回错误信息
//            return $response->withStatus(500)->withBody(new SwooleStream($data));

            //自定义异常处理
            return $this->httpResponse->redirect('/auth/login?redirect='.$redirct);
        }
        return $response;
    }

    /**
     * 是否对异常进行处理.
     *
     * @param Throwable $throwable
     *
     * @return bool
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
